﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace IM.Easy.Core.Cache
{
    public class MemoryCacheProvider : ICache
    {
        private readonly IMemoryCache _memoryCache;
        private readonly HashSet<string> _cacheKeys;  // 用来存储所有缓存项的 key

        public MemoryCacheProvider(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
            _cacheKeys = [];
        }

        /// <summary>
        /// 设置缓存项
        /// </summary>
        public void Set(string key, object value, TimeSpan? absoluteExpirationRelativeToNow = null)
        {
            var options = new MemoryCacheEntryOptions();
            if (absoluteExpirationRelativeToNow.HasValue)
            {
                options.SetAbsoluteExpiration(absoluteExpirationRelativeToNow.Value);
            }

            _memoryCache.Set(key, value, options);
            _cacheKeys.Add(key);  // 将 key 添加到集合中，供清空时使用
        }

        /// <summary>
        /// 获取缓存项
        /// </summary>
        public T Get<T>(string key)
        {
            _memoryCache.TryGetValue(key, out T value);
            return value;
        }


        /// <summary>
        /// 移除缓存项
        /// </summary>
        public void Remove(string key)
        {
            _memoryCache.Remove(key);
            _cacheKeys.Remove(key);  // 移除 key
        }

        /// <summary>
        /// 检查缓存项是否存在
        /// </summary>
        public bool Exists(string key)
        {
            return _memoryCache.TryGetValue(key, out _);
        }

        /// <summary>
        /// 清空所有缓存项
        /// </summary>
        public void Clear()
        {
            // 遍历所有缓存项的 key 并移除
            foreach (var key in _cacheKeys)
            {
                _memoryCache.Remove(key);
            }
            _cacheKeys.Clear();  // 清空记录的 key 列表
        }

        public IDictionary<string, string> GetAll()
        {
            var allEntries = new Dictionary<string, string>();
            foreach (var key in _cacheKeys)
            {
                if (_memoryCache.TryGetValue(key, out string value))
                {
                    allEntries[key] = value;
                }
            }
            return allEntries;
        }

        /// <summary>
        /// 通过正则删除
        /// </summary>
        /// <param name="keyPattern"></param>
        public void RemoveByPattern(string keyPattern)
        {
            if (string.IsNullOrEmpty(keyPattern)) return;

            var regexPattern = new Regex(
                Regex.Escape(keyPattern)
                     .Replace(@"\*", ".*")
                     .Replace(@"\?", "."),
                RegexOptions.IgnoreCase | RegexOptions.Compiled
            );

            var keysToRemove = _cacheKeys
                .Where(key => regexPattern.IsMatch(key))
                .ToList();

            foreach (var key in keysToRemove)
            {
                _memoryCache.Remove(key);
                _cacheKeys.Remove(key);
            }
        }
    }

}
